package com.huawei.esdk.tp.professional.local.impl.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;

import com.huawei.esdk.platform.professional.local.impl.utils.RSA2048Utils;

public abstract class Encrypt
{
    private static final Logger LOGGER = Logger.getLogger(Encrypt.class.getName());
    
    public static String getEncryptPassword(String randomkey, String key)
    {
        if (StringUtils.isNullOrEmpty(key) || StringUtils.isNullOrEmpty(randomkey))
        {
            return null;
        }
        byte[] encryptPassword;
        MessageDigest md;
        String ep = null;
        try
        {
            md = MessageDigest.getInstance("SHA-256");
            
            md.update(key.getBytes("UTF-8"));
            encryptPassword = md.digest();
            
            StringBuilder sBuilder = new StringBuilder();
            sBuilder.append(BytesUtils.bytes2HexString(encryptPassword));
            String password = sBuilder.toString();
            
            sBuilder = new StringBuilder();
            
            sBuilder.append(BytesUtils.bytes2HexString(Base64Utils.getFromBASE64(randomkey)));
            password += sBuilder.toString();
            
            md.update(password.getBytes("UTF-8"));
            encryptPassword = md.digest();
            
            sBuilder.append(BytesUtils.bytes2HexString(encryptPassword));
            ep = Base64Utils.encode(encryptPassword);
        }
        catch (NoSuchAlgorithmException e)
        {
            LOGGER.log(java.util.logging.Level.WARNING, "Exception happened in getEncryptPassword()", e);
        }
        catch (UnsupportedEncodingException e)
        {
            LOGGER.log(java.util.logging.Level.WARNING, "Exception happened in getEncryptPassword()", e);
        }
        return ep;
    }
    
    public static String getEncryptPwd(String pwd)
        throws Exception
    {
        String transmissionMode = PropertiesUtils.getValue("sensitive.information.transmission.mode");
        String result = null;
        
        if (StringUtils.isNullOrEmpty(pwd))
        {
            return null;
        }
        
        if ("RSA2048".equalsIgnoreCase(transmissionMode))
        {
            result = Base64Utils.encode(RSA2048Utils.encode(pwd.getBytes("UTF-8")));
        }
        else if ("AES128_fixed".equalsIgnoreCase(transmissionMode))
        {
            result = Base64Utils.encode(AESCbc128Utils.encode(pwd.getBytes("UTF-8")));
        }
        else if ("Plaintext".equalsIgnoreCase(transmissionMode))
        {
            result = pwd;
        }
        else
        {
            result = Base64Utils.encode(AES128Utils.encode(pwd.getBytes("UTF-8")));
        }
        
        return result;
    }
    
}
